import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:word_range_client/widgets/general/PartingLine.dart';

import '../../widgets/general/Toastification.dart';

class SetRevisionPlanView extends StatelessWidget {
  const SetRevisionPlanView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("设置学习计划"),
      ),
      body: const _SetRevisionPlanBody(),
    );
  }
}

class _SetRevisionPlanBody extends StatefulWidget {
  const _SetRevisionPlanBody({super.key});


  @override
  State<_SetRevisionPlanBody> createState() => _SetRevisionPlanBodyState();
}

class _SetRevisionPlanBodyState extends State<_SetRevisionPlanBody> {

  late final TextEditingController _newWordTextEditingController;
  late final TextEditingController _oldWordTextEditingController;

  @override
  void initState() {
    super.initState();
    _newWordTextEditingController = TextEditingController();
    _oldWordTextEditingController = TextEditingController();
    _loadData();
  }

  //回显数据
  Future<void> _loadData() async {
    final prefs = await SharedPreferences.getInstance();
    if (prefs.containsKey("newWordCount")) {
      int newWordCount = prefs.getInt("newWordCount")!;
      _newWordTextEditingController.text = newWordCount.toString();
    }else{
      _newWordTextEditingController.text = "10";
    }
    if (prefs.containsKey("oldWordCount")) {
      int oldWordCount = prefs.getInt("oldWordCount")!;
      _oldWordTextEditingController.text = oldWordCount.toString();
    }else{
      _oldWordTextEditingController.text = "20";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
          padding: const EdgeInsets.all(15),
          child: ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 900),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const SizedBox(),
                Column(
                  children: [
                    _NewWordCard(newWordTextEditingController: _newWordTextEditingController,),
                    const SizedBox(height: 5,),
                    _OldWordCard(oldWordTextEditingController: _oldWordTextEditingController,)
                  ],
                ),
                _SaveButton(newWordTextEditingController: _newWordTextEditingController,
                    oldWordTextEditingController: _oldWordTextEditingController)
              ],
            ),
          )
      ),
    );
  }
}


class _NewWordCard extends StatelessWidget {
  const _NewWordCard({super.key, required this.newWordTextEditingController});

  final TextEditingController newWordTextEditingController;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: 150,
      child: Card(
        color: Theme.of(context).colorScheme.primary,
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    "每日新学词汇量:",
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w600,
                      color: Theme.of(context).colorScheme.onSecondary,
                    ),
                  ),
                  SizedBox(
                    width: 100, // 设置输入框的宽度
                    child: _Input(
                      textEditingController: newWordTextEditingController,
                      onChanged: (s) {},
                    ),
                  ),
                ],
              ),
              PartingLine(color: Theme.of(context).colorScheme.onSecondary.withValues(alpha: 0.7),),
              Text(
                "本项影响学习计划的每日学习新词数量，系统会根据用户指定的学习计划调整每日学习新词数量，请根据自身情况选择。",
                style: TextStyle(
                    fontSize: 12,
                    color: Theme.of(context).colorScheme.onSecondary
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _OldWordCard extends StatelessWidget {
  const _OldWordCard({super.key, required this.oldWordTextEditingController});

  final TextEditingController oldWordTextEditingController;

  @override

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: 150,
      child: Card(
        color: Theme.of(context).colorScheme.primary,
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    "每日复习词汇量:",
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w600,
                      color: Theme.of(context).colorScheme.onSecondary,
                    ),
                  ),
                  SizedBox(
                    width: 100, // 设置输入框的宽度
                    child: _Input(
                      textEditingController: oldWordTextEditingController,
                      onChanged: (s) {},
                    ),
                  ),
                ],
              ),
              PartingLine(color: Theme.of(context).colorScheme.onSecondary.withValues(alpha: 0.7),),
              Text(
                "本项影响学习计划的每日复习词汇量，请根据自身情况填写。建议选择每日新词数量的2倍。",
                style: TextStyle(
                    fontSize: 12,
                    color: Theme.of(context).colorScheme.onSecondary
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _Input extends StatefulWidget {
  const _Input({super.key, required this.textEditingController, required this.onChanged});

  final TextEditingController textEditingController;
  final Function(String) onChanged;

  @override
  State<_Input> createState() => _InputState();
}

class _InputState extends State<_Input> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(3),
      child: SizedBox(
        height: 35,
        child: TextField(
          controller: widget.textEditingController,
          textAlign: TextAlign.center,
          cursorColor: Colors.white,
          style: TextStyle(
            fontSize: 17,
            color: Theme.of(context).colorScheme.onSecondary,
          ),
          keyboardType: TextInputType.number,
          onChanged: widget.onChanged,
          decoration:  InputDecoration(
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(
                color: Theme.of(context).colorScheme.onSecondary,
              ),
            ),
            focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
                color: Theme.of(context).colorScheme.onSecondary,
              ),
            ),
            hintText: '',
          ),
        ),
      )
    );
  }
}

class _SaveButton extends StatefulWidget {
  const _SaveButton({super.key, required this.newWordTextEditingController, required this.oldWordTextEditingController});

  final TextEditingController newWordTextEditingController;
  final TextEditingController oldWordTextEditingController;

  @override
  State<_SaveButton> createState() => _SaveButtonState();
}

class _SaveButtonState extends State<_SaveButton> {
  //保存数据
  Future<void> _saveData() async {
    final prefs = await SharedPreferences.getInstance();
    Toastification toastification = Toastification(context: context);
    String newWordText = widget.newWordTextEditingController.text;
    String oldWordText = widget.oldWordTextEditingController.text;
    // 两个必须为整数且大于0
    try{
      if (newWordText.isNotEmpty && oldWordText.isNotEmpty) {
        int newWordCount = int.parse(newWordText);
        int oldWordCount = int.parse(oldWordText);
        if (newWordCount > 0 && oldWordCount > 0) {
          prefs.setInt("newWordCount", newWordCount);
          prefs.setInt("oldWordCount", oldWordCount);
          _goBack();
        }else{
          toastification.showError("您输入的值有误，请输入正整数");
        }
      }else{
        toastification.showError('请输入内容');
      }
    }catch(e){
      toastification.showError('$e');
    }
  }

  // 返回上一页
  void _goBack() {
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: ElevatedButton(
          style: ButtonStyle(
            backgroundColor: WidgetStateProperty.all(Theme.of(context).colorScheme.primary),
            shape: WidgetStateProperty.all(
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(13)),
            ),
          ),
          onPressed: _saveData,
          child: const Text(
            "保存并退出",
            style: TextStyle(
                fontSize: 17,
                color: Colors.white
            ),
          )
      ),
    );
  }
}

